<template>
  <div id="home">
    <Login
      v-if="showLoginPage"
      @login-success="onLoginSuccess($event)"
      :systemName="systemName"
    />
    <Dashboard
      v-if="showDashboard"
      @logout="onLogout"
      :username="getUserName"
      :systemName="systemName"
    />
  </div>
</template>

<script>
import { message } from 'ant-design-vue'
import Dashboard from './components/Dashboard'
import Login from './components/Login'
// import HelloWorld from './components/HelloWorld'

export default {
  name: 'App',
  data() {
    return {
      showLoginPage: false,
      showDashboard: false,
      username: '',
      systemName: '材料基因数据管理平台',
    }
  },
  components: {
    Login,
    Dashboard,
  },
  mounted() {
    this.authenticate()
  },
  methods: {
    runLogin() {
      this.showLoginPage = true
      this.showDashboard = false
    },
    runDashboard() {
      this.showLoginPage = false
      this.showDashboard = true
    },
    // 登录成功时，切换页面内容
    onLoginSuccess(res) {
      message.success('登录成功！')
      this.username = res.data.username
      this.runDashboard()
    },
    onLogout() {
      this.runLogin()
    },
    // 认证用户的登录状态
    authenticate() {
      this.axios
        .get('/is_authenticated/')
        .then((res) => {
          const data = res.data
          // 如果已是登录状态，切换页面内容
          if ('username' in data) {
            // console.log('认证成功！')
            this.runDashboard()
            this.username = data.username
          } else {
            this.runLogin()
            // console.log('认证失败！')
          }
        })
        .catch((error) => {
          console.log('Error', error.message)
        })
    },
  },
  computed: {
    getUserName() {
      // console.log(this.username)
      // console.log('haha')
      // console.log(this.username)
      return this.username
    },
  },
}
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  /* text-align: center; */
  color: #2c3e50;
  /* margin-top: 60px; */
}
</style>
